const http = require('http')
const url = require('url')

const PORT = process.env.PORT || 3000

function jsonResponse(res, code, obj) {
  const body = JSON.stringify(obj)
  res.writeHead(code, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) })
  res.end(body)
}

function handleRequest(req, res) {
  const parsed = url.parse(req.url, true)
  if (req.method === 'GET' && parsed.pathname === '/') {
    const body = `<html><body><h1>Simple Node App</h1><ul><li><a href="/api/hello">/api/hello</a></li><li><a href="/api/time">/api/time</a></li></ul></body></html>`
    res.writeHead(200, { 'Content-Type': 'text/html' })
    return res.end(body)
  }

  if (req.method === 'GET' && parsed.pathname === '/api/hello') {
    return jsonResponse(res, 200, { message: 'hello world' })
  }

  if (req.method === 'GET' && parsed.pathname === '/api/time') {
    return jsonResponse(res, 200, { time: new Date().toISOString(), uptime: process.uptime() })
  }

  if (req.method === 'POST' && parsed.pathname === '/api/echo') {
    let data = ''
    req.on('data', chunk => { data += chunk })
    req.on('end', () => {
      try {
        const obj = JSON.parse(data || '{}')
        return jsonResponse(res, 200, obj)
      } catch (e) {
        return jsonResponse(res, 400, { error: 'invalid json' })
      }
    })
    return
  }

  res.writeHead(404, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ error: 'not found' }))
}

if (require.main === module) {
  const server = http.createServer(handleRequest)
  server.listen(PORT, () => {
    console.log(`server listening on port ${PORT}`)
  })
}

module.exports = { handleRequest }
